import { CheckAns } from "./CheckAns";

namespace LeetCode0567CheckInclusion {

    function checkInclusion(s1: string, s2: string): boolean {
        if (!s1 || !s2 || s1.length > s2.length)
            return false;
        // 处理s1字符串，因为题目要求不需要顺序，仅统计字符个数；且全小写字符，顾size=26的数组即可
        let aryS1: number[] = (new Array(26)).fill(0);
        // 处理s2字符串前s1.length长度，因为题设s2.length>=s1.length
        let aryS2: number[] = (new Array(26)).fill(0);
        // 循环遍历s1.length，统计s1字符，顺便统计s2前s1.length字符串
        const charACode: number = 'a'.charCodeAt(0);
        const s1Len: number = s1.length;
        for (let i = 0; i < s1Len; i++) {
            const code1: number = s1.charCodeAt(i) - charACode;
            aryS1[code1]++;
            const code2: number = s2.charCodeAt(i) - charACode;
            aryS2[code2]++;
        }
        // 比较一下字符串是否相等
        let isEqual: boolean = aryS1.every((v: number, idx: number) => {
            return v == aryS2[idx];
        });
        // 题意仅需找到一处匹配即可
        if (isEqual) return true;
        // 后续遍历，用双指针对数组aryS2直接进行维护，节省统计开销
        let right = s1Len;
        while (right < s2.length) {
            // fixed the aryS2
            aryS2[s2.charCodeAt(right) - charACode]++;
            aryS2[s2.charCodeAt(right - s1Len) - charACode]--;
            // 比较一下字符串是否相等，题意仅需找到一处匹配即可
            isEqual = aryS1.every((v: number, idx: number) => {
                return v == aryS2[idx];
            });
            if (isEqual)
                return true;
            right++;
        }
        return false;
    };


    // test
    const testData: { s1: string, s2: string, ans: boolean }[] = [
        { s1: "ab", s2: "eidbaooo", ans: true },
        { s1: "ab", s2: "eidboaoo", ans: false }
    ];
    for (const data of testData) {
        const ans = checkInclusion(data.s1, data.s2);
        CheckAns(data, ans);
    }
}